<?php

namespace app\common\model\option;

use app\common\model\option\Log as OptionLog;
use app\common\model\order\Order;
use app\common\model\red\Log;
use app\common\model\User;
use think\Db;
use think\Log as ThinkLog;
use think\Model;


class Option extends Model
{





    // 表名
    protected $name = 'option';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];










    public function admin()
    {
        return $this->belongsTo('app\common\model\Admin', 'id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public static function market()
    {
        $freight = Order::whereTime('paytime', 'yesterday')->where('status', '>', 0)->sum('freight');
        $payMoney = Order::whereTime('paytime', 'yesterday')->where('status', '>', 0)->sum('pay_money');
        $where['invalidtime'] = ['>', time()];
        $where['status'] = ['=', 'normal'];
        $where['state'] = ['=', '1'];
        $option = User::sum('options');
        $total = bcsub($payMoney, $freight ?? 0, 2);
        return $option ? bcdiv(bcmul($total, 0.1, 2), $option, 2) : $option;
    }

    /**
     * YS释放
     *
     */
    public static function option_release()
    {
        $check = Option::whereTime('createtime', 'today')->find();
        if ($check) {
            return '';
        }
        Db::startTrans();
        try {
            $data = Option::order('id desc')->find();
            if (!$data) {
                $param = [
                    'options' => 1000,
                    'day' => 1,
                    'total' => 1000,
                ];
            } else {
                $option = $data->options + 70;
                $param = [
                    'options' => $option,
                    'day' =>  $data->day + 1,
                    'total' => $data->total + $option,
                ];
            }
            $res = Option::create($param);
            if ($res) {
                $where['invalidtime'] = ['>', time()];
                $where['status'] = ['=', 'normal'];
                $where['state'] = ['=', '1'];
                $logs = Log::all($where);

                //总分红包效率
                $total = Log::where($where)->sum('efficiency');
                foreach ($logs as $v) {
                    //个人分红包比例
                    $todaypro = $v->efficiency / $total;
                    //YS分配数量
                    $option = bcmul($res->options, $todaypro, 4);
                    //每日YS分配
                    OptionLog::income($v->user_id, $option, 2, 100, $v->sn, $res->id);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            ThinkLog::error($e->getMessage());
            Db::rollback();
        }
    }
}
